package de.smarthome;

import java.util.List;

import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import de.smarthome.adapter.TabsAdapter;
import de.smarthome.database.DatabaseHandler;
import de.smarthome.rooms.RoomData;
import de.smarthome.rooms.RoomFragment;
import de.smarthome.rooms.RoomFragment.RoomDataProvider;

public class MainActivity extends FragmentActivity implements RoomDataProvider {

	ViewPager ViewPager;
	TabsAdapter TabsAdapter;
	DatabaseHandler dbHandler;
	static MainActivity mainActivity;
	private List<RoomData> rooms;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		dbHandler = new DatabaseHandler(this);
		dbHandler.initDBSettings();
		mainActivity = this;
		this.rooms = dbHandler.getAllRoomAttrib();

		buildTabs();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("tab", getActionBar().getSelectedNavigationIndex());

	}

	private void buildTabs() {
		ViewPager viewPager = new ViewPager(this);
		viewPager.setId(R.id.pager);
		setContentView(viewPager);

		ActionBar bar = getActionBar();
		// Create a new Action bar and set title to strings.xml

		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		bar.setTitle(R.string.app_name);

		// Attach the Tabs to the fragment classes and set the tab title.
		TabsAdapter tabsAdapter = new TabsAdapter(this, viewPager);

		for (int i = 0; i < rooms.size(); i++) {

			Bundle bundle = new Bundle();
			bundle.putInt("index", i);
			tabsAdapter.addTab(
					bar.newTab().setText(rooms.get(i).getRoomName()),
					RoomFragment.class, bundle);

		}

	}

	public static MainActivity getInstance() {
		return mainActivity;
	}

	@Override
	public RoomData getRoomObject(int index) {
		return rooms.get(index);
	}

}